import time
import wave

import pyaudio
from PyQt5.QtCore import QThread, pyqtSignal


class Voice(QThread):
    voiceFlag = pyqtSignal(int)

    def __init__(self, voice_text, parent=None):
        super(Voice, self).__init__(parent)
        self.text = voice_text

    def run(self):
        # print(self.text)
        try:
            self.play_audio()
        except:
            time.sleep(1)
            pass
        self.quit()

    def play_audio(self):
        CHUNK = 1024
        filepath = 'audio/' + self.text + '.wav'
        wf = wave.open(filepath, 'rb')
        data = wf.readframes(CHUNK)
        p = pyaudio.PyAudio()
        FORMAT = p.get_format_from_width(wf.getsampwidth())
        CHANNELS = wf.getnchannels()
        RATE = wf.getframerate()
        # print('FORMAT: {} \nCHANNELS: {} \nRATE: {}'.format(FORMAT, CHANNELS, RATE))
        stream = p.open(format=FORMAT,
                        channels=CHANNELS,
                        rate=RATE,
                        frames_per_buffer=CHUNK,
                        output=True)
        while len(data) > 0:
            stream.write(data)
            data = wf.readframes(CHUNK)
